from flask import request
from flask_jwt_extended import jwt_required
from flask_restx import Namespace, Resource, fields
from datetime import datetime

from app1 import db
from app1.models import Zbfwb_RemedyGongdan

# 创建 Flask-RESTx 命名空间
ns_remedy_gongdan = Namespace('ns_remedy_gongdan', description='工单管理')

# ========================== 输入/输出模型 ==========================
# 输出模型
remedy_gongdan_model = ns_remedy_gongdan.model('Zbfwb_RemedyGongdan', {
    'TicketID': fields.String(required=True, description='工单编号'),
    'SRMType': fields.String(required=True, description='工单类型'),
    'Chr_Cer1': fields.String(required=True, description='证书1'),
    'Chr_Cer2': fields.String(required=True, description='证书2'),
    'Chr_Cer3': fields.String(description='证书3'),
    'Chr_SRM_Status': fields.String(description='状态'),
    'Status_Reason': fields.String(description='状态原因'),
    'SystemName': fields.String(description='系统名称'),
    'Detailed_Decription': fields.String(description='描述'),
    'Assigned_Support_Company': fields.String(description='支持公司'),
    'Assigned_Group': fields.String(description='分配组'),
    'Assignee': fields.String(description='分配人'),
    'Submiter': fields.String(description='提交人'),
    'Customer': fields.String(description='客户'),
    'Contact_Company': fields.String(description='联系公司'),
    'Organization': fields.String(description='组织'),
    'Department': fields.String(description='部门'),
    'CreateTime': fields.String(description='创建时间'),
    'SolveTime': fields.String(description='解决时间'),
    'Priority': fields.String(description='优先级'),
    'cDat_AppTime': fields.String(description='应用时间'),
    'cDat_EccalastTime': fields.String(description='最近更新时间'),
    'cSel_EsclationYN': fields.String(description='是否升级'),
    'RecTime': fields.String(description='接收时间'),
    'SendHx': fields.String(description='是否发送hx')
})

# 统一响应模型
response_remedy_gongdan_model = ns_remedy_gongdan.model('Response_RemedyGongdan', {
    'message': fields.Nested(ns_remedy_gongdan.model('Message_RemedyGongdan', {
        'result': fields.Integer(description='0=成功 1=失败'),
        'result_text': fields.String(description='结果描述'),
        'count': fields.Integer(description='总记录数'),
        'data': fields.List(fields.Nested(remedy_gongdan_model))
    }))
})

# 条件 + 分页查询模型
remedy_gongdan_query_model = ns_remedy_gongdan.model('RemedyGongdanQuery', {
    'TicketID': fields.String(default='', description='工单编号'),
    'SRMType': fields.String(default='', description='工单类型'),
    'SystemName': fields.String(default='', description='系统名称'),
    'Assignee': fields.String(default='', description='分配人'),
    'Submiter': fields.String(default='', description='提交人'),
    'Chr_SRM_Status': fields.String(default='', description='状态'),
    'page': fields.Integer(default=1, description='页码'),
    'size': fields.Integer(default=20, description='每页条数')
})

# 新增模型
remedy_gongdan_add_model = ns_remedy_gongdan.model('RemedyGongdanAdd', {
    'TicketID': fields.String(required=True, description='工单编号'),
    'SRMType': fields.String(required=True, description='工单类型'),
    'Chr_Cer1': fields.String(required=True, description='证书1'),
    'Chr_Cer2': fields.String(required=True, description='证书2'),
    'Chr_Cer3': fields.String(description='证书3'),
    'Chr_SRM_Status': fields.String(description='状态'),
    'Status_Reason': fields.String(description='状态原因'),
    'SystemName': fields.String(description='系统名称'),
    'Detailed_Decription': fields.String(description='描述'),
    'Assigned_Support_Company': fields.String(description='支持公司'),
    'Assigned_Group': fields.String(description='分配组'),
    'Assignee': fields.String(description='分配人'),
    'Submiter': fields.String(description='提交人'),
    'Customer': fields.String(description='客户'),
    'Contact_Company': fields.String(description='联系公司'),
    'Organization': fields.String(description='组织'),
    'Department': fields.String(description='部门'),
    'CreateTime': fields.String(description='创建时间'),
    'SolveTime': fields.String(description='解决时间'),
    'Priority': fields.String(description='优先级'),
    'cDat_AppTime': fields.String(description='应用时间'),
    'cDat_EccalastTime': fields.String(description='最近更新时间'),
    'cSel_EsclationYN': fields.String(description='是否升级'),
    'RecTime': fields.String(description='接收时间'),
    'SendHx': fields.String(description='是否发送hx')
})

# 删除模型
remedy_gongdan_del_model = ns_remedy_gongdan.model('RemedyGongdanDelete', {
    'TicketID': fields.String(required=True, description='工单编号')
})

# 更新模型
remedy_gongdan_upd_model = ns_remedy_gongdan.model('RemedyGongdanUpdate', {
    'TicketID': fields.String(required=True, description='工单编号'),
    'SRMType': fields.String(required=True, description='工单类型'),
    'Chr_Cer1': fields.String(required=True, description='证书1'),
    'Chr_Cer2': fields.String(required=True, description='证书2'),
    'Chr_Cer3': fields.String(description='证书3'),
    'Chr_SRM_Status': fields.String(description='状态'),
    'Status_Reason': fields.String(description='状态原因'),
    'SystemName': fields.String(description='系统名称'),
    'Detailed_Decription': fields.String(description='描述'),
    'Assigned_Support_Company': fields.String(description='支持公司'),
    'Assigned_Group': fields.String(description='分配组'),
    'Assignee': fields.String(description='分配人'),
    'Submiter': fields.String(description='提交人'),
    'Customer': fields.String(description='客户'),
    'Contact_Company': fields.String(description='联系公司'),
    'Organization': fields.String(description='组织'),
    'Department': fields.String(description='部门'),
    'CreateTime': fields.String(description='创建时间'),
    'SolveTime': fields.String(description='解决时间'),
    'Priority': fields.String(description='优先级'),
    'cDat_AppTime': fields.String(description='应用时间'),
    'cDat_EccalastTime': fields.String(description='最近更新时间'),
    'cSel_EsclationYN': fields.String(description='是否升级'),
    'RecTime': fields.String(description='接收时间'),
    'SendHx': fields.String(description='是否发送hx')
})

# 单条查询模型
remedy_gongdan_get_model = ns_remedy_gongdan.model('RemedyGongdanGet', {
    'TicketID': fields.String(required=True, description='工单编号')
})


# ========================== 1. 分页+条件查询 ==========================
@ns_remedy_gongdan.route('/remedy_gongdan_list')
class RemedyGongdanListResource(Resource):
    # @jwt_required()
    @ns_remedy_gongdan.expect(remedy_gongdan_query_model)
    @ns_remedy_gongdan.marshal_with(response_remedy_gongdan_model)
    def post(self):
        """条件+分页查询工单信息"""
        data = request.get_json()

        query = Zbfwb_RemedyGongdan.query

        # 条件过滤
        if data.get('TicketID'):
            query = query.filter(Zbfwb_RemedyGongdan.TicketID.like(f"%{data['TicketID']}%"))
        if data.get('SRMType'):
            query = query.filter(Zbfwb_RemedyGongdan.SRMType.like(f"%{data['SRMType']}%"))
        if data.get('SystemName'):
            query = query.filter(Zbfwb_RemedyGongdan.SystemName.like(f"%{data['SystemName']}%"))
        if data.get('Assignee'):
            query = query.filter(Zbfwb_RemedyGongdan.Assignee.like(f"%{data['Assignee']}%"))
        if data.get('Submiter'):
            query = query.filter(Zbfwb_RemedyGongdan.Submiter.like(f"%{data['Submiter']}%"))
        if data.get('Chr_SRM_Status'):
            query = query.filter(Zbfwb_RemedyGongdan.Chr_SRM_Status.like(f"%{data['Chr_SRM_Status']}%"))

        page = max(1, data.get('page', 1))
        size = max(1, data.get('size', 20))
        total = query.count()
        rows = query.limit(size).offset((page - 1) * size).all()

        return {
            'message': {
                'result': 0,
                'result_text': '查询成功',
                'count': total,
                'data': [r.to_dict() for r in rows]
            }
        }


# ========================== 2. 新增 ==========================
@ns_remedy_gongdan.route('/remedy_gongdan_create')
class RemedyGongdanCreateResource(Resource):
    # @jwt_required()
    @ns_remedy_gongdan.expect(remedy_gongdan_add_model)
    @ns_remedy_gongdan.marshal_with(response_remedy_gongdan_model)
    def post(self):
        """新增工单信息"""
        data = request.get_json()

        # 必填字段校验
        required_fields = ['TicketID', 'SRMType', 'Chr_Cer1', 'Chr_Cer2']
        missing = [f for f in required_fields if not data.get(f)]
        if missing:
            return {
                'message': {
                    'result': 1,
                    'result_text': f'以下字段不能为空: {", ".join(missing)}',
                    'count': 0, 'data': []
                }
            }, 400

        # 检查工单编号是否已存在
        if Zbfwb_RemedyGongdan.query.filter_by(TicketID=data['TicketID']).first():
            return {
                'message': {
                    'result': 1,
                    'result_text': '该工单编号已存在',
                    'count': 0, 'data': []
                }
            }, 400

        # 处理时间字段
        def parse_datetime(dt_str):
            if dt_str:
                try:
                    return datetime.fromisoformat(dt_str.replace('Z', '+00:00'))
                except:
                    return None
            return None

        new_row = Zbfwb_RemedyGongdan(
            TicketID=data['TicketID'],
            SRMType=data['SRMType'],
            Chr_Cer1=data['Chr_Cer1'],
            Chr_Cer2=data['Chr_Cer2'],
            Chr_Cer3=data.get('Chr_Cer3'),
            Chr_SRM_Status=data.get('Chr_SRM_Status'),
            Status_Reason=data.get('Status_Reason'),
            SystemName=data.get('SystemName'),
            Detailed_Decription=data.get('Detailed_Decription'),
            Assigned_Support_Company=data.get('Assigned_Support_Company'),
            Assigned_Group=data.get('Assigned_Group'),
            Assignee=data.get('Assignee'),
            Submiter=data.get('Submiter'),
            Customer=data.get('Customer'),
            Contact_Company=data.get('Contact_Company'),
            Organization=data.get('Organization'),
            Department=data.get('Department'),
            CreateTime=parse_datetime(data.get('CreateTime')),
            SolveTime=parse_datetime(data.get('SolveTime')),
            Priority=data.get('Priority'),
            cDat_AppTime=parse_datetime(data.get('cDat_AppTime')),
            cDat_EccalastTime=parse_datetime(data.get('cDat_EccalastTime')),
            cSel_EsclationYN=data.get('cSel_EsclationYN'),
            RecTime=parse_datetime(data.get('RecTime')),
            SendHx=data.get('SendHx')
        )

        try:
            db.session.add(new_row)
            db.session.commit()
            return {
                'message': {
                    'result': 0,
                    'result_text': '创建成功',
                    'count': 1,
                    'data': [new_row.to_dict()]
                }
            }, 201
        except Exception as e:
            db.session.rollback()
            return {
                'message': {
                    'result': 1,
                    'result_text': f'创建失败: {str(e)}',
                    'count': 0, 'data': []
                }
            }, 500


# ========================== 3. 删除 ==========================
@ns_remedy_gongdan.route('/remedy_gongdan_delete')
class RemedyGongdanDeleteResource(Resource):
    # @jwt_required()
    @ns_remedy_gongdan.expect(remedy_gongdan_del_model)
    @ns_remedy_gongdan.marshal_with(response_remedy_gongdan_model)
    def post(self):
        """根据工单编号删除工单信息"""
        data = request.get_json()

        row = Zbfwb_RemedyGongdan.query.filter_by(TicketID=data['TicketID']).first()

        if not row:
            return {
                'message': {
                    'result': 1,
                    'result_text': '工单不存在',
                    'count': 0, 'data': []
                }
            }, 404

        try:
            db.session.delete(row)
            db.session.commit()
            return {
                'message': {
                    'result': 0,
                    'result_text': '删除成功',
                    'count': 1,
                    'data': [row.to_dict()]
                }
            }
        except Exception as e:
            db.session.rollback()
            return {
                'message': {
                    'result': 1,
                    'result_text': f'删除失败: {str(e)}',
                    'count': 0, 'data': []
                }
            }, 500


# ========================== 4. 更新 ==========================
@ns_remedy_gongdan.route('/remedy_gongdan_update')
class RemedyGongdanUpdateResource(Resource):
    # @jwt_required()
    @ns_remedy_gongdan.expect(remedy_gongdan_upd_model)
    @ns_remedy_gongdan.marshal_with(response_remedy_gongdan_model)
    def post(self):
        """更新工单信息"""
        data = request.get_json()

        # 必填字段校验
        required_fields = ['SRMType', 'Chr_Cer1', 'Chr_Cer2']
        missing = [f for f in required_fields if not data.get(f)]
        if missing:
            return {
                'message': {
                    'result': 1,
                    'result_text': f'以下字段不能为空: {", ".join(missing)}',
                    'count': 0, 'data': []
                }
            }, 400

        row = Zbfwb_RemedyGongdan.query.filter_by(TicketID=data['TicketID']).first()

        if not row:
            return {
                'message': {
                    'result': 1,
                    'result_text': '工单不存在',
                    'count': 0, 'data': []
                }
            }, 404

        try:
            # 处理时间字段
            def parse_datetime(dt_str):
                if dt_str:
                    try:
                        return datetime.fromisoformat(dt_str.replace('Z', '+00:00'))
                    except:
                        return None
                return None

            # 更新字段
            row.SRMType = data['SRMType']
            row.Chr_Cer1 = data['Chr_Cer1']
            row.Chr_Cer2 = data['Chr_Cer2']
            row.Chr_Cer3 = data.get('Chr_Cer3')
            row.Chr_SRM_Status = data.get('Chr_SRM_Status')
            row.Status_Reason = data.get('Status_Reason')
            row.SystemName = data.get('SystemName')
            row.Detailed_Decription = data.get('Detailed_Decription')
            row.Assigned_Support_Company = data.get('Assigned_Support_Company')
            row.Assigned_Group = data.get('Assigned_Group')
            row.Assignee = data.get('Assignee')
            row.Submiter = data.get('Submiter')
            row.Customer = data.get('Customer')
            row.Contact_Company = data.get('Contact_Company')
            row.Organization = data.get('Organization')
            row.Department = data.get('Department')
            row.CreateTime = parse_datetime(data.get('CreateTime'))
            row.SolveTime = parse_datetime(data.get('SolveTime'))
            row.Priority = data.get('Priority')
            row.cDat_AppTime = parse_datetime(data.get('cDat_AppTime'))
            row.cDat_EccalastTime = parse_datetime(data.get('cDat_EccalastTime'))
            row.cSel_EsclationYN = data.get('cSel_EsclationYN')
            row.RecTime = parse_datetime(data.get('RecTime'))
            row.SendHx = data.get('SendHx')

            db.session.commit()
            return {
                'message': {
                    'result': 0,
                    'result_text': '更新成功',
                    'count': 1,
                    'data': [row.to_dict()]
                }
            }
        except Exception as e:
            db.session.rollback()
            return {
                'message': {
                    'result': 1,
                    'result_text': f'更新失败: {str(e)}',
                    'count': 0, 'data': []
                }
            }, 500


# ========================== 5. 单条查询 ==========================
@ns_remedy_gongdan.route('/remedy_gongdan_get')
class RemedyGongdanGetResource(Resource):
    # @jwt_required()
    @ns_remedy_gongdan.expect(remedy_gongdan_get_model)
    @ns_remedy_gongdan.marshal_with(response_remedy_gongdan_model)
    def post(self):
        """根据工单编号查询单条工单信息"""
        data = request.get_json()

        ticket_id = data.get('TicketID', '').strip()
        if not ticket_id:
            return {
                'message': {
                    'result': 1,
                    'result_text': 'TicketID 不能为空',
                    'count': 0,
                    'data': []
                }
            }, 400

        row = Zbfwb_RemedyGongdan.query.filter_by(TicketID=ticket_id).first()

        if not row:
            return {
                'message': {
                    'result': 1,
                    'result_text': '工单不存在',
                    'count': 0,
                    'data': []
                }
            }, 404

        return {
            'message': {
                'result': 0,
                'result_text': '查询成功',
                'count': 1,
                'data': [row.to_dict()]
            }
        }